﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Giaiphongmatbang.BLL;
using Giaiphongmatbang.DataModel;
using System.Data;

namespace Giaiphongmatbang
{
    public partial class addObject : System.Web.UI.Page
    {
        public static DataTable tblLand;
        QLGPMBEntities db = new QLGPMBEntities();
        int ProjectID
        {
            get { return (int)ViewState["ProjectID"]; }
            set { ViewState["ProjectID"] = value; }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ProjectID = int.Parse(Request.QueryString["id"]);
                Project pr = new ProjectsRepository().GetByID(ProjectID);
                ltrProjectName.Text = pr.ProjectName;
                ltrInvestor.Text = pr.Investor;
                Title = ":: Thêm mới đối tượng - Dự án " + pr.ProjectName + " ::";
                BindDataDropDown();
                Bindddl_LandType();
                BuildtblLand();
            }
        }

        protected void BindDataDropDown()
        {
            drdVillage.DataSource = new VillagesRepostory().GetByDistrictID((int)Utility.Enum.DistrictCode.HungNguyen);
            drdVillage.DataValueField = "VillageID";
            drdVillage.DataTextField = "VillageName";
            drdVillage.DataBind();
        }

        protected void Bindddl_LandType()
        {
            DataAccess.GPMBDataContext datacontext = new DataAccess.GPMBDataContext();
            ddlLandType.DataSource = datacontext.uspGetAllLandType();
            ddlLandType.DataTextField = "LandName";
            ddlLandType.DataValueField = "LandID";
            ddlLandType.DataBind();
        }

        public void BuildtblLand()
        {
            tblLand = new DataTable();
            tblLand.Columns.Add("Index", typeof(int));
            tblLand.Columns.Add("LandID", typeof(int));
            tblLand.Columns.Add("LandName", typeof(string));
            tblLand.Columns.Add("Plot", typeof(string));
            tblLand.Columns.Add("ofMap", typeof(int));
            tblLand.Columns.Add("Place", typeof(string));
            tblLand.Columns.Add("Hamlet", typeof(string));
            tblLand.Columns.Add("Position", typeof(string));
            tblLand.Columns.Add("Areas", typeof(float));
            tblLand.Columns.Add("Unit", typeof(string));
            tblLand.Columns.Add("UnitPrice", typeof(float));
            tblLand.Columns.Add("Coefficient", typeof(float));
            tblLand.Columns.Add("UserAreas", typeof(float));
            tblLand.Columns.Add("toAmounts", typeof(float));
            tblLand.Columns.Add("Origin", typeof(string));
            tblLand.Columns.Add("Description", typeof(string));
        }

        protected void btnAddLand_Click(object sender, EventArgs e)
        {
            int index = tblLand.Rows.Count + 1;
            int id = int.Parse(ddlLandType.SelectedValue);
            string landname = ddlLandType.SelectedItem.ToString();
            string plot = txtPlot.Text;
            int map = int.Parse(txtofMap.Text);
            string place = txtPlace.Text;
            string hamlet = txtHamlet.Text;
            string position = txtPosition.Text;
            float areas = float.Parse(txtAreas.Text);
            float unit = float.Parse(txtUnitPrice.Text);
            float userareas = float.Parse(txtUserAreas.Text);
            float toAmounts = areas * unit;
            string origin = txtOrigin.Text;
            string description = txtDescription.Text;
            tblLand.Rows.Add(index, id, landname, plot, map, place, hamlet, position, areas, "m2", unit, 1, userareas, toAmounts, origin, description);
            rpt_LandDamage.DataSource = tblLand;
            rpt_LandDamage.DataBind();
            Bindddl_LandType();
        }

        protected void rpt_LandDamage_ItemCommand(object sender, RepeaterCommandEventArgs e)
        {
            string command = e.CommandName;
            try
            {
                string index = e.CommandArgument.ToString();
                if(command.Equals("ibtnDelete"))
                {
                    int i = 0;
                    while (i < tblLand.Rows.Count)
                    {
                        DataRow dr = tblLand.Rows[i];
                        if (dr[0].ToString() == index)
                        {
                            tblLand.Rows.Remove(dr);
                        }
                        i++;
                    }
                }
                rpt_LandDamage.DataSource = tblLand;
                rpt_LandDamage.DataBind();
            }
            catch { }
        }

        #region Repeater InsertLand


        protected void btnNewLand_Click(object sender, EventArgs e)
        {
            BindSourceddlLandType();
        }

        protected void BindSourceddlLandType()
        {
            DataAccess.GPMBDataContext datacontext = new DataAccess.GPMBDataContext();
            ddlLandType.DataSource = datacontext.uspGetAllLandType();
            ddlLandType.DataValueField = "LandID";
            ddlLandType.DataTextField = "LandName";
            ddlLandType.DataBind();
        }

        #endregion
        #region Repeater Insert Trees
        string imgTree(int id, bool expand)
        {
            if (!db.Trees.Any(p => p.ParentID == id))
                return "/Images/not.gif";
            if (db.Trees.Any(p => p.ParentID == id) && expand == true)
                return "/Images/plus.gif";
            return "/Images/minus.gif";
        }
        protected void btnInsertTree_Click(object sender, EventArgs e)
        {
            BindDataRepeaterInsertTree();
            btnInsertTree.Visible = false;
        }
        protected void BindDataRepeaterInsertTree()
        {
            rptInsertTree.DataSource = new TreesRepository().GetByParentID(0);
            rptInsertTree.DataBind();
        }

        protected void rptInsertTree_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.Footer && e.Item.ItemType != ListItemType.Header)
            {
                int ID = int.Parse(((HiddenField)e.Item.FindControl("hdf")).Value);
                ImageButton imgButton = (ImageButton)e.Item.FindControl("imgButton");
                TextBox txt = (TextBox)e.Item.FindControl("txtQuantity");
                CheckBox chk = e.Item.FindControl("chk") as CheckBox;
                if (new TreesRepository().HasChild(ID))
                {
                    txt.Visible = false;
                    chk.Visible = false;
                }
                imgButton.ImageUrl = imgTree(ID, true);
                imgButton.AlternateText = "   ";
            }
        }

        protected void imgButton1_Click(object sender, EventArgs e)
        {
            ImageButton btn = (ImageButton)sender;
            int ID = int.Parse(((HiddenField)btn.Parent.FindControl("hdf")).Value);
            HiddenField hdf = (HiddenField)btn.Parent.FindControl("hdfexpand");
            bool expand = Convert.ToBoolean(hdf.Value);
            Repeater rpt = btn.Parent.FindControl("rptInsertTree") as Repeater;
            btn.ImageUrl = imgTree(ID, !expand);
            if (expand == true)
            {
                hdf.Value = "false";
                rpt.DataSource = new TreesRepository().GetByParentID(ID);
            }
            else
            {
                hdf.Value = "true";
                rpt.DataSource = null;
            }
            rpt.DataBind();
        }
        #endregion
        #region Repeater Insert House
        string imgHouse(int id, bool expand)
        {
            if (!db.HouseTypes.Any(p => p.ParentID == id))
                return "/Images/not.gif";
            if (db.HouseTypes.Any(p => p.ParentID == id) && expand == true)
                return "/Images/plus.gif";
            return "/Images/minus.gif";
        }
        protected void btnInsertHouse_Click(object sender, EventArgs e)
        {
            BindDataRepeaterInsertHouse();
            btnInsertHouse.Visible = false;
        }
        protected void BindDataRepeaterInsertHouse()
        {
            rptInsertHouse.DataSource = new HouseTypesRepository().GetByParentID(0);
            rptInsertHouse.DataBind();
        }

        protected void rptInsertHouse_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.Footer && e.Item.ItemType != ListItemType.Header)
            {
                int ID = int.Parse(((HiddenField)e.Item.FindControl("hdf")).Value);
                ImageButton imgButton = (ImageButton)e.Item.FindControl("imgButton");
                TextBox txt = (TextBox)e.Item.FindControl("txtQuantity");
                CheckBox chk = e.Item.FindControl("chk") as CheckBox;
                if (new HouseTypesRepository().HasChild(ID))
                {
                    txt.Visible = false;
                    chk.Visible = false;
                }
                imgButton.ImageUrl = imgHouse(ID, true);
                imgButton.AlternateText = "   ";
            }
        }

        protected void imgButton2_Click(object sender, EventArgs e)
        {
            ImageButton btn = (ImageButton)sender;
            int ID = int.Parse(((HiddenField)btn.Parent.FindControl("hdf")).Value);
            HiddenField hdf = (HiddenField)btn.Parent.FindControl("hdfexpand");
            bool expand = Convert.ToBoolean(hdf.Value);
            Repeater rpt = btn.Parent.FindControl("rptInsertHouse") as Repeater;
            btn.ImageUrl = imgHouse(ID, !expand);
            if (expand == true)
            {
                hdf.Value = "false";
                rpt.DataSource = new HouseTypesRepository().GetByParentID(ID);
            }
            else
            {
                hdf.Value = "true";
                rpt.DataSource = null;
            }
            rpt.DataBind();
        }
        #endregion
        #region Repeater Insert Building
        string imgBuilding(int id, bool expand)
        {
            if (!db.Buildings.Any(p => p.ParentID == id))
                return "/Images/not.gif";
            if (db.Buildings.Any(p => p.ParentID == id) && expand == true)
                return "/Images/plus.gif";
            return "/Images/minus.gif";
        }
        protected void btnInsertBuilding_Click(object sender, EventArgs e)
        {
            BindDataRepeaterInsertBuilding();
            btnInsertBuilding.Visible = false;
        }
        protected void BindDataRepeaterInsertBuilding()
        {
            rptInsertBuilding.DataSource = new BuildingsRepository().GetByParentID(0);
            rptInsertBuilding.DataBind();
        }

        protected void rptInsertBuilding_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.Footer && e.Item.ItemType != ListItemType.Header)
            {
                int ID = int.Parse(((HiddenField)e.Item.FindControl("hdf")).Value);
                ImageButton imgButton = (ImageButton)e.Item.FindControl("imgButton");
                TextBox txt = (TextBox)e.Item.FindControl("txtQuantity");
                TextBox txtRemaining = e.Item.FindControl("txtRemainingPercent") as TextBox;
                CheckBox chk = e.Item.FindControl("chk") as CheckBox;
                if (new BuildingsRepository().HasChild(ID))
                {
                    txtRemaining.Visible = false;
                    txt.Visible = false;
                    chk.Visible = false;
                }
                imgButton.ImageUrl = imgBuilding(ID, true);
                imgButton.AlternateText = "   ";
            }
        }

        protected void imgButton3_Click(object sender, EventArgs e)
        {
            ImageButton btn = (ImageButton)sender;
            int ID = int.Parse(((HiddenField)btn.Parent.FindControl("hdf")).Value);
            HiddenField hdf = (HiddenField)btn.Parent.FindControl("hdfexpand");
            bool expand = Convert.ToBoolean(hdf.Value);
            Repeater rpt = btn.Parent.FindControl("rptInsertBuilding") as Repeater;
            btn.ImageUrl = imgBuilding(ID, !expand);
            if (expand == true)
            {
                hdf.Value = "false";
                rpt.DataSource = new BuildingsRepository().GetByParentID(ID);
            }
            else
            {
                hdf.Value = "true";
                rpt.DataSource = null;
            }
            rpt.DataBind();
        }
        #endregion
        #region Repeater Insert Graves
        string imgGrave(int id, bool expand)
        {
            if (!db.Graves.Any(p => p.ParentID == id))
                return "/Images/not.gif";
            if (db.Graves.Any(p => p.ParentID == id) && expand == true)
                return "/Images/plus.gif";
            return "/Images/minus.gif";
        }
        protected void btnInsertGrave_Click(object sender, EventArgs e)
        {
            BindDataRepeaterInsertGrave();
            btnInsertGrave.Visible = false;
        }
        protected void BindDataRepeaterInsertGrave()
        {
            rptInsertGrave.DataSource = new GravesRepository().GetByParentID(0);
            rptInsertGrave.DataBind();
        }

        protected void rptInsertGrave_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.Footer && e.Item.ItemType != ListItemType.Header)
            {
                int ID = int.Parse(((HiddenField)e.Item.FindControl("hdf")).Value);
                ImageButton imgButton = (ImageButton)e.Item.FindControl("imgButton");
                TextBox txt = (TextBox)e.Item.FindControl("txtQuantity");
                CheckBox chk = e.Item.FindControl("chk") as CheckBox;
                if (new GravesRepository().HasChild(ID))
                {
                    txt.Visible = false;
                    chk.Visible = false;
                }
                imgButton.ImageUrl = imgGrave(ID, true);
                imgButton.AlternateText = "   ";
            }
        }

        protected void imgButton4_Click(object sender, EventArgs e)
        {
            ImageButton btn = (ImageButton)sender;
            int ID = int.Parse(((HiddenField)btn.Parent.FindControl("hdf")).Value);
            HiddenField hdf = (HiddenField)btn.Parent.FindControl("hdfexpand");
            bool expand = Convert.ToBoolean(hdf.Value);
            Repeater rpt = btn.Parent.FindControl("rptInsertGrave") as Repeater;
            btn.ImageUrl = imgGrave(ID, !expand);
            if (expand == true)
            {
                hdf.Value = "false";
                rpt.DataSource = new GravesRepository().GetByParentID(ID);
            }
            else
            {
                hdf.Value = "true";
                rpt.DataSource = null;
            }
            rpt.DataBind();
        }
        #endregion
        #region Command

        protected void AddInventoryLand(int projectid, string CMND, int landID, string plot, int ofMap, string place, string hamlet, string position, float areas, string unit, float unitprice, float userareas, string origin, string description)
        {
            try
            {
                DataAccess.GPMBDataContext datacontext = new DataAccess.GPMBDataContext();
                DataAccess.Land land = datacontext.uspGetLandByID(landID).FirstOrDefault();
                datacontext.uspInsertInvenLand(projectid, CMND, landID, plot, ofMap, place, hamlet, position, areas, unit, unitprice, land.Coefficient, userareas, land.isSupport, unitprice * areas, origin, description);
            }
            catch { }
        }

        protected void btnInsertSupportMove_Click(object sender, EventArgs e)
        {
            btnInsertSupportMove.Visible = false;
            ucSupportMove1.Visible = true;
            ucSupportMove1.BindData();
        }

        protected void btnInsertSupportRent_Click(object sender, EventArgs e)
        {
            btnInsertSupportRent.Visible = false;
            ucSupportRent1.Visible = true;
            ucSupportRent1.BindData();
        }

        protected void btnInsertSupportStabilize_Click(object sender, EventArgs e)
        {
            btnSupportStabilize.Visible = false;
            ucSupportStabilize1.Visible = true;
            ucSupportStabilize1.BindData();
        }

        protected void btnInsertSupportJob_Click(object sender, EventArgs e)
        {
            btnSupportJob.Visible = false;
            ucSupportJob1.Visible = true;
            ucSupportJob1.BindData();
        }
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Session["ProjectID"] = ProjectID;
            Response.Redirect("/duan.aspx");
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            int count = 0;
            string CMND = Guid.NewGuid().ToString().Substring(0, 10);
            while (db.Inventories.Any(p => p.CMND.Equals(CMND) && p.ProjectID == ProjectID) && count < 10)
            {
                CMND = Guid.NewGuid().ToString().Substring(0, 10);
            }
            
            int VillageID = int.Parse(drdVillage.SelectedValue);
            int? MemberCount = null;
            try
            {
                MemberCount = int.Parse(txtMemberCount.Text);
            }
            catch { }
            if (!db.HouseHolds.Any(p => p.CMND == CMND))
            {
                new HouseHoldRepository().Insert(CMND, txtHouseHold.Text, txtAddress.Text, Convert.ToBoolean(drdGender.SelectedValue),
                                        txtPhoneNumber.Text, MemberCount, VillageID);
            }
                       

            Inventory invent = new Inventory
            {
                ProjectID = ProjectID,
                CMND = CMND,
                HouseHold = db.HouseHolds.FirstOrDefault(p=>p.CMND.Equals(CMND)),
                Project = db.Projects.First(p=>p.ProjectID == ProjectID),
                InventoryDate = System.DateTime.Now
            };
            db.AddToInventories(invent);
            db.SaveChanges();

            string[] split = new string[] { "|$--$|" };
            string[] separator = new string[] { "$--$" };
            //string[] arrLand = hdfLand.Value.Split(split, StringSplitOptions.RemoveEmptyEntries);
            //foreach (var item in arrLand)
            //{
            //    string[] value = item.Split(separator, StringSplitOptions.None);
            //    int LandID = int.Parse(value[0]);
            //    InventoryLand inventLand = new InventoryLand
            //    {
            //        Inventory = db.Inventories.FirstOrDefault(p => p.ProjectID == ProjectID && p.CMND == CMND),
            //        Land = db.Lands.FirstOrDefault(p => p.LandID == LandID),
            //        Areas = double.Parse("0" + value[1]),
            //        isSupport = Convert.ToBoolean(value[2])
            //    };
            //    db.SaveChanges();
            //}
            for (int i = 0; i < tblLand.Rows.Count; i++ )
            {
                int landid = int.Parse(tblLand.Rows[i][1].ToString());
                string plot = tblLand.Rows[i][3].ToString();
                int ofmap = int.Parse(tblLand.Rows[i][4].ToString());
                string place = tblLand.Rows[i][5].ToString();
                string hamlet = tblLand.Rows[i][6].ToString();
                string position = tblLand.Rows[i][7].ToString();
                float areas = float.Parse(tblLand.Rows[i][8].ToString());
                string unit = tblLand.Rows[i][9].ToString();
                float unitprice = float.Parse(tblLand.Rows[i][10].ToString());
                float coefficient = float.Parse(tblLand.Rows[i][11].ToString());
                float userareas = float.Parse(tblLand.Rows[i][12].ToString());
                float toamounts = float.Parse(tblLand.Rows[i][13].ToString());
                string origin = tblLand.Rows[i][14].ToString();
                string description = tblLand.Rows[i][15].ToString();
                AddInventoryLand(ProjectID, CMND, landid, plot, ofmap, place, hamlet, position, areas, unit, unitprice, userareas, origin, description);

            }
            

            string[] arrTree = hdfTree.Value.Split(split, StringSplitOptions.RemoveEmptyEntries);
            foreach (var item in arrTree)
            {
                string[] value = item.Split(separator, StringSplitOptions.None);
                int TreeID = int.Parse(value[0]);
                try
                {
                    InventoryTree inventTree = new InventoryTree
                    {
                        Inventory = db.Inventories.FirstOrDefault(p => p.ProjectID == ProjectID && p.CMND == CMND),
                        Tree = db.Trees.FirstOrDefault(p => p.TreeID == TreeID),
                        Quantity = double.Parse("0" + value[1])
                    };
                }
                catch { }
                db.SaveChanges();
            }

            string[] arrHouse = hdfHouse.Value.Split(split, StringSplitOptions.RemoveEmptyEntries);
            foreach (var item in arrHouse)
            {
                string[] value = item.Split(separator, StringSplitOptions.None);
                int HouseID = int.Parse(value[0]);
                try
                {
                    InventoryHouse inventTree = new InventoryHouse
                    {
                        Inventory = db.Inventories.FirstOrDefault(p => p.ProjectID == ProjectID && p.CMND == CMND),
                        HouseType = db.HouseTypes.FirstOrDefault(p => p.HouseID == HouseID),
                        Quantity = double.Parse("0" + value[1])
                    };
                }
                catch { }
                db.SaveChanges();
            }

            string[] arrBuilding = hdfBuilding.Value.Split(split, StringSplitOptions.RemoveEmptyEntries);
            foreach (var item in arrBuilding)
            {
                string[] value = item.Split(separator, StringSplitOptions.None);
                int BuildingID = int.Parse(value[0]);
                try
                {
                    InventoryBuilding inventTree = new InventoryBuilding
                    {
                        Inventory = db.Inventories.FirstOrDefault(p => p.ProjectID == ProjectID && p.CMND == CMND),
                        Building = db.Buildings.FirstOrDefault(p => p.BuildingID == BuildingID),
                        Quantity = double.Parse("0" + value[1]),
                        RemainingPercent = double.Parse("0" + value[2])
                    };
                }
                catch { }
                db.SaveChanges();
            }

            string[] arrGrave = hdfGrave.Value.Split(split, StringSplitOptions.RemoveEmptyEntries);
            foreach (var item in arrGrave)
            {
                try
                {
                    string[] value = item.Split(separator, StringSplitOptions.None);
                    int GraveID = int.Parse(value[0]);
                    InventoryGrave inventTree = new InventoryGrave
                    {
                        Inventory = db.Inventories.FirstOrDefault(p => p.ProjectID == ProjectID && p.CMND == CMND),
                        Grave = db.Graves.FirstOrDefault(p => p.GraveID == GraveID),
                        Quantity = double.Parse(value[1])
                    };
                }
                catch { }
                db.SaveChanges();
            }

            int? SupportMoveID = null;
            try { SupportMoveID = int.Parse(hdfSupportMove.Value); }
            catch { }
            int? SupportRentID = null;
            int? QuantityRent = null;
            try
            {
                string[] value = hdfSupportRent.Value.Split(separator, StringSplitOptions.None);
                SupportRentID = int.Parse(value[0]);
                QuantityRent = int.Parse(value[1]);
            }
            catch { };
            int? SupportStabilizeID = null;
            int? QuantityStabilize = null;
            try
            {
                string[] value = hdfSupportStabilize.Value.Split(separator, StringSplitOptions.None);
                SupportStabilizeID = int.Parse(value[0]);
                QuantityStabilize = int.Parse(value[1]);
            }
            catch { }
            int? SupportJobID = null;
            try
            {
                SupportJobID = int.Parse(hdfSupportJob.Value);
            }
            catch { }

            Support support = new Support();
            support.ProjectID = ProjectID;
            support.CMND = CMND;
            support.Project = db.Projects.FirstOrDefault(p => p.ProjectID == ProjectID);
            support.HouseHold = db.HouseHolds.FirstOrDefault(p => p.CMND.Equals(CMND));
            if (SupportMoveID.HasValue)
            {
                support.SupportMove = db.SupportMoves.FirstOrDefault(p => p.SupportMoveID == SupportMoveID.Value);
            }
            if (SupportRentID.HasValue)
            {
                support.SupportRent = db.SupportRents.FirstOrDefault(p => p.SupporRenttID == SupportRentID.Value);
                support.QuantityRent = QuantityRent.Value;
            }
            if (SupportStabilizeID.HasValue)
            {
                support.SupportStabilize = db.SupportStabilizes.FirstOrDefault(p => p.SupportStabilizeID == SupportStabilizeID.Value);
                support.QuantityStabilize = QuantityStabilize.Value;
            }
            if (SupportJobID.HasValue)
            {
                support.SupportJob = db.SupportJobs.FirstOrDefault(p => p.SuportJobID == SupportJobID.Value);
            }
            db.AddToSupports(support);
            db.SaveChanges();
            if (!string.IsNullOrEmpty(hdfSupportOther.Value.Trim()))
            {
                string []values = hdfSupportOther.Value.Split(split, StringSplitOptions.RemoveEmptyEntries);
                foreach (var item in values)
                {
                    string[] value = item.Split(separator, StringSplitOptions.None);
                    decimal Price = decimal.Parse("0" + value[1]);
                    string SupportName = value[0];
                    SupportOther spOther = new SupportOther
                    {
                        Support = db.Supports.FirstOrDefault(p=>p.CMND.Equals(CMND) && p.ProjectID==ProjectID),
                        SupportName = SupportName,
                        UnitPrice = Price
                    };                   
                    db.SaveChanges();
                }
            }
            Session["ProjectID"] = ProjectID;
            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('Thêm mới thành công!'); window.location='duan.aspx';", true);

        }
        #endregion
    }
}